package com.crazy.mybatis.gerenator.service.java;

import org.springframework.stereotype.Component;

import com.crazy.mybatis.gerenator.service.Context;
import com.crazy.mybatis.gerenator.service.common.MethodEnum;
import com.crazy.mybatis.gerenator.service.util.TypeUtil;

@Component
public class JavaBuilder {

	public ClassMetaData build(Context context) {
		ClassMetaData meta = new ClassMetaData();
		meta.setClassName(context.getBeanName());
		meta.setClassType("class");
		meta.setPackageName(context.getBeanPackage());
		meta.getPropertyList().addAll(context.getPropertyList());
		for (String property : context.getPropertyList()) {
			String propertyType = context.getPropertyTypeMap().get(property);
			meta.getTypeMap().put(property, TypeUtil.getShortName(propertyType));
			if (propertyType.indexOf("java.lang") == -1) {
				meta.getImportClasses().add(propertyType);
			}
		}
		return meta;
	}

	public ClassMetaData buildMethodMeta(Context context) {
		ClassMetaData meta = new ClassMetaData();
		meta.setClassName(context.getBeanName() + "Mapper");
		meta.setClassType("interface");
		meta.setPackageName(context.getMapperPackage());
		meta.getImportClasses().add(context.getBeanPackage() + "." + context.getBeanName());
		for (MethodEnum me : context.getMethodSet()) {
			if (me == MethodEnum.INSERT || me == MethodEnum.INSERT_SELECTIVE
					|| me == MethodEnum.UPDATE_BY_PRIMARY_KEY 
					|| me == MethodEnum.UPDATE_BY_PRIMARY_KEY_SELECTIVE) {
				MapperMethodMetaData mm = new MapperMethodMetaData();
				mm.setReturnClassName("int");
				mm.setMethodName(me.getValue());
				mm.setParameter(lowerCaseFirst(context.getBeanName()));
				mm.setParameterClassName(context.getBeanName());
				meta.getMethodList().add(mm);
			} else if (me == MethodEnum.SELECT_BY_PRIMARY_KEY) {
				MapperMethodMetaData mm = new MapperMethodMetaData();
				mm.setReturnClassName(context.getBeanName());
				mm.setMethodName(me.getValue());
				String primaryProperty = context.getColumnPropertyMap().get(context.getPrimaryKey());
				mm.setParameter(primaryProperty);
				mm.setParameterClassName(TypeUtil.getShortName(context.getPropertyTypeMap().get(primaryProperty)));
				meta.getMethodList().add(mm);
			}
		}
		
		
		return meta;
	}

	public String lowerCaseFirst(String str) {
		return str.substring(0, 1).toLowerCase() + str.substring(1);
	}
}
